/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.web.entity.YjCommissionRatio;
import com.jeeplus.modules.web.service.YjCommissionRatioService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.WxAgentsLevel;
import com.jeeplus.modules.web.entity.WxAgentsRecording;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.service.WxAgentsLevelService;
import com.jeeplus.modules.web.service.WxAgentsRecordingService;
import com.jeeplus.modules.web.service.WxAgentsService;

/**
 * 代理商Controller
 * @author rongjie
 * @version 2017-08-06
 */
@Controller
@RequestMapping(value = "${adminPath}/web/wxAgents")
public class WxAgentsController extends BaseController {

	@Autowired
	private WxAgentsService wxAgentsService;
	@Autowired
	private WxAgentsRecordingService wxAgentsRecordingService;

	@Autowired
	private WxAgentsLevelService wxAgentsLevelService;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;
	@Autowired
	private YjCommissionRatioService yjCommissionRatioService;

	private final static int AGENT_LEVEL_YWY = 4;//前台选择门店级别代理商时传入的值
	private final static int AGENT_LEVEL_SHOP = 3;//前台选择门店级别代理商时传入的值

	private final static String ALREADY_APPROVAL_STATUS = "1"; //已审核状态
	private final static String NOT_APPROVAL_STATUS = "0"; //未审核状态


	@ModelAttribute
	public WxAgents get(@RequestParam(required=false) String id) {
		WxAgents entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wxAgentsService.get(id);
		}
		if (entity == null){
			entity = new WxAgents();
		}
		return entity;
	}

	/**
	 * 代理商列表页面
	 */
	@RequiresPermissions("web:wxAgents:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/web/wxAgentsList";
	}

		/**
	 * 代理商列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgents:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(WxAgents wxAgents, HttpServletRequest request, HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		//加入权限控制，当前用户如果不是管理员，只能查看有权限的部分数据
		if (!currentUser.getId().equals("1")) {
			//由于此处查询的参数都封装在agents里，故只设置agents的id即可，避免此处查出的agents信息覆盖查询参数
			WxAgents temp = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			wxAgents.setId(temp.getId());
		}
		Page<WxAgents> page = wxAgentsService.findPageMore(new Page<WxAgents>(request, response), wxAgents);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑代理商表单页面
	 */
	@RequiresPermissions(value={"web:wxAgents:view","web:wxAgents:add","web:wxAgents:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WxAgents wxAgents, Model model) {
		model.addAttribute("wxAgents", wxAgents);
		if(wxAgents.getRatioId()!=null){
			YjCommissionRatio commissionRatio = yjCommissionRatioService.get(wxAgents.getRatioId());
			JSONArray array = JSONObject.parseArray(commissionRatio.getConfig());
			Map<String,JSONObject> map = new HashMap<>();
			for (int i = 0; i < array.size(); i++) {
				map.put(array.getJSONObject(i).getString("deviceType"),array.getJSONObject(i));
			}
			model.addAttribute("commissionRatio", map);
		}

		//代理商层级列表
		List<WxAgentsLevel> levelList = wxAgentsLevelService.getAgentsLevelList();
		Map<Integer, String> levelTypeMap = new HashMap<Integer, String>();
		for(WxAgentsLevel level : levelList){
			levelTypeMap.put(level.getAgentLevel(), level.getAgentType());
		}
		if(StringUtils.isBlank(wxAgents.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}else{
			//如果为编辑，则需要回显当前代理商父层级代理商及父代理商信息
			//如果门店级别的话，门店可以隶属于一级或二级代理
			List<WxAgents> parentLevelWxAgents = new ArrayList<WxAgents>();
			if(wxAgents.getAgentLevel() == AGENT_LEVEL_SHOP || wxAgents.getAgentLevel() == AGENT_LEVEL_YWY){
				parentLevelWxAgents = wxAgentsService.getByParentsLevel(AGENT_LEVEL_SHOP, ALREADY_APPROVAL_STATUS);
				if(wxAgents.getAgentLevel() == AGENT_LEVEL_SHOP ){
					parentLevelWxAgents.addAll(wxAgentsService.getByLevel(AGENT_LEVEL_YWY, ALREADY_APPROVAL_STATUS));
				}
			}
			else{
				parentLevelWxAgents = wxAgentsService.getByLevel(wxAgents.getAgentLevel() - 1, ALREADY_APPROVAL_STATUS);
			}
			//拼接类似于:13609896235(一级代理商),方便用户知道此代理商所在层级
			for(WxAgents agents : parentLevelWxAgents){
				if(null != agents){
					agents.setUserName(agents.getUserName() + "(" + levelTypeMap.get(agents.getAgentLevel()) + ")");
				}
			}
			WxAgents parentWxAgent = wxAgentsService.get(String.valueOf(wxAgents.getParentId()));
			if(null != parentWxAgent){
				parentWxAgent.setUserName(parentWxAgent.getUserName() + "(" + levelTypeMap.get(parentWxAgent.getAgentLevel()) + ")");
			}
			model.addAttribute("parentWxAgent", parentWxAgent);
			model.addAttribute("parentLevelWxAgents", parentLevelWxAgents);
		}

		// 加载代理商列表
		//List<WxAgents> list = wxAgentsService.findList(new WxAgents());
		//model.addAttribute("list", list);
		model.addAttribute("levelList", levelList);
		model.addAttribute("deviceType", DictUtils.getDictList("deviceType"));

		model.addAttribute("message", wxAgents.getMessage());
		return "modules/web/wxAgentsForm";
	}

	/**
	 * 根据所选代理商层级，加载其父级代理商
	 */
	@ResponseBody
	@RequiresPermissions(value={"web:wxAgents:view","web:wxAgents:add","web:wxAgents:edit"},logical=Logical.OR)
	@RequestMapping(value = "/geAgentsByLevel/{agentLevel}")
	public Map<String, Object> getParentAgentsByLevel(@PathVariable int agentLevel, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> map  = new HashMap<String, Object>();
		if(agentLevel > 0){
			//如果门店级别的话，门店可以隶属于一级或二级代理
			if(agentLevel == AGENT_LEVEL_SHOP ||agentLevel == AGENT_LEVEL_YWY){
				List<WxAgents> parentLevelWxAgents = wxAgentsService.getByParentsLevel(AGENT_LEVEL_SHOP, ALREADY_APPROVAL_STATUS);
				if(agentLevel == AGENT_LEVEL_SHOP ){
					parentLevelWxAgents.addAll(wxAgentsService.getByLevel(AGENT_LEVEL_YWY, ALREADY_APPROVAL_STATUS));
				}
				map.put("agentList", parentLevelWxAgents);
			}else{
				//代理商层级agent_level，数字越小，代表层级越高，0为最高一级，公司
				List<WxAgents> wxAgents = wxAgentsService.getByLevel(--agentLevel, ALREADY_APPROVAL_STATUS);
				map.put("agentList", wxAgents);
			}
		}
		return map;
	}

	/**
	 * 分销商收入记录列表页面
	 */
	@RequiresPermissions("web:wxAgents:view")
	@RequestMapping(value = {"{agentId}/recordDetails"})
	public String recordDetails(@PathVariable String agentId, Model model) {
		model.addAttribute("agentId", agentId);
		return "modules/web/wxAgentsRecordDetails";
	}

	/**
	 * 分销商收入记录列表数据
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgents:view")
	@RequestMapping(value = "{agentId}/getRecordDetails")
	public Map<String, Object> getRecordDetails(@PathVariable String agentId, HttpServletRequest request, HttpServletResponse response, Model model) {
		WxAgents wxAgents = wxAgentsService.get(agentId);
		WxAgentsRecording wxAgentsRecording = new WxAgentsRecording();
		WxAgents wxAgentsReq = new WxAgents();
		wxAgentsReq.setId(wxAgents.getId());
		wxAgentsReq.setUserName(wxAgents.getUserName());
		wxAgentsRecording.setAgents(wxAgentsReq);
		Page<WxAgentsRecording> page = wxAgentsRecordingService.findPage(new Page<WxAgentsRecording>(request, response), wxAgentsRecording);
		return getBootstrapData(page);
	}

	/**
	 * 保存代理商
	 */
	@RequiresPermissions(value={"web:wxAgents:add","web:wxAgents:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WxAgents wxAgents, Model model, RedirectAttributes redirectAttributes,String config) throws Exception{
		if (!beanValidator(model, wxAgents)){
			return form(wxAgents, model);
		}
		//如果wxAgent的ID不为空，为修改操作
		if(StringUtils.isNotBlank(wxAgents.getId())){
			//修改操作，通过查询wxAgentID之外，是否还有账号为当前userName的代理商
			List<WxAgents> temp = wxAgentsService.getByUsernameWithoutSelf(wxAgents.getUserName(), wxAgents.getId());
			//如果除当前代理商之外，还有代理商userName为当前传入值，则不能修改，会冲突
			if(null != temp && temp.size() > 0){
				wxAgents.setMessage("该代理商账号已注册");
				return form(wxAgents, model);
			}
			//修改操作，需要获取修改前的userName字段，用于关联更新sys_user表数据
			WxAgents tempAgent = wxAgentsService.findUniqueByProperty("id", wxAgents.getId());
			wxAgents.setUser(new User());
			wxAgents.getUser().setMobile(tempAgent.getUserName());
		}else{
			//新增操作，通过代理商userName判断是否重复
			WxAgents temp = wxAgentsService.getByUsername(wxAgents.getUserName());
			if(null != temp){
				wxAgents.setMessage("该代理商账号已注册");
				return form(wxAgents, model);
			}
		}
		/*WxAgents temp = wxAgentsService.getByUsername(wxAgents.getUserName());
		//如当前wxAgents为新增记录，而通过wxAgents的userName能查出数据，则判定账号重复
		if (wxAgents.getIsNewRecord() && temp!=null){
			wxAgents.setMessage("该代理商账号已注册");
			return form(wxAgents, model);
		}
		//如当前wxAgents非新增记录，而查出来的数据userName
		if (!wxAgents.getIsNewRecord() && temp!=null && !temp.getUserName().equals(wxAgents.getUser().getMobile())){
			wxAgents.setMessage("该代理商账号已注册");
			return form(wxAgents, model);
		}*/
		if(wxAgents.getAgentLevel() == AGENT_LEVEL_SHOP){
			YjCommissionRatio yjCommissionRatio = new YjCommissionRatio();
			yjCommissionRatio.setName(wxAgents.getUserName());
			yjCommissionRatio.setConfig(StringEscapeUtils.unescapeHtml4(config.trim()));
			yjCommissionRatio.setId(wxAgents.getRatioId());
			yjCommissionRatioService.save(yjCommissionRatio);
			wxAgents.setRatioId(yjCommissionRatio.getId());
		}

		//新增或编辑表单保存
		wxAgentsService.save(wxAgents);//保存
		addMessage(redirectAttributes, "保存代理商成功");
		return "redirect:"+Global.getAdminPath()+"/web/wxAgents/?repage";
	}

	/**
	 * 删除代理商
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgents:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(WxAgents wxAgents, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		wxAgentsService.delete(wxAgents);
		j.setMsg("删除代理商成功");
		return j;
	}

	/**
	 * 批量删除代理商
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgents:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			wxAgentsService.delete(wxAgentsService.get(id));
		}
		j.setMsg("删除代理商成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("web:wxAgents:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(WxAgents wxAgents, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "代理商"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WxAgents> page = wxAgentsService.findPage(new Page<WxAgents>(request, response, -1), wxAgents);
    		new ExportExcel("代理商", WxAgents.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出代理商记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("web:wxAgents:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WxAgents> list = ei.getDataList(WxAgents.class);
			for (WxAgents wxAgents : list){
				try{
					wxAgentsService.save(wxAgents);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条代理商记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条代理商记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入代理商失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxAgents/?repage";
    }

	/**
	 * 下载导入代理商数据模板
	 */
	@RequiresPermissions("web:wxAgents:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "代理商数据导入模板.xlsx";
    		List<WxAgents> list = Lists.newArrayList();
    		new ExportExcel("代理商数据", WxAgents.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/wxAgents/?repage";
    }

}
